
//
//  DisplayViewController.m
//  iOS_2D_RecordPath
//
//  Created by PC on 15/8/3.
//  Copyright (c) 2015年 FENGSHENG. All rights reserved.
//

#import "DisplayViewController.h"
#import "MAMutablePolylineRenderer.h"
#import "NKRouteRecord.h"
#import "Util.h"
#import "CustomAnnotationView.h"
#import "NKPointAnnotation.h"
#import "NKLookAnnotationViewController.h"

@interface DisplayViewController()<MAMapViewDelegate>
{
    NSMutableArray *_tracking;
}

@property (nonatomic, strong) NKRouteRecord *record;

@property (nonatomic, strong) MAMapView *mapView;

@property (nonatomic, strong) NSArray  *fileArray;

@property (nonatomic, strong) MAPointAnnotation *myLocation;

@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;

@end


@implementation DisplayViewController

#pragma mark - Life Cycle

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self initMapView];
    
    [self showRoute];
    
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [[EMCDDeviceManager sharedInstance] stopPlaying];
}


- (void)initMapView {
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.zoomLevel = 20.0;
    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    self.mapView.showsCompass = YES;
    self.mapView.showsScale = YES;
    self.mapView.rotateCameraEnabled = NO;
    self.mapView.scaleOrigin = CGPointMake(120, NKScreenHeight - 25);
    self.mapView.compassOrigin = CGPointMake(NKScreenWidth - 40, NKScreenHeight - 40);
    self.mapView.showsIndoorMap = NO;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
}

- (void)showRoute
{
    if (self.record == nil || self.record.locationArray.count == 0)
    {
        NSLog(@"invaled route");
    }
    
    [self initDisplayRoutePolyline];
    [self initDisplayAnnotationView];
}

#pragma mark - Interface

- (void)setRecord:(NKRouteRecord *)record
{
    if (_record == record)
    {
        return;
    }
    
    _record = record;
}



- (void)initDisplayRoutePolyline
{

    NSArray< NKLocation*> *tracePoints = self.record.locationArray;
    
    if (tracePoints.count < 2)
    {
        return;
    }
    
    MAPointAnnotation *startPoint = [[MAPointAnnotation alloc] init];
    NKLocation *startLocation = tracePoints.firstObject;
    startPoint.coordinate = CLLocationCoordinate2DMake(startLocation.nk_latitude, startLocation.nk_longitude);
    startPoint.title = @"start";
    [self.mapView addAnnotation:startPoint];
    
    MAPointAnnotation *endPoint = [[MAPointAnnotation alloc] init];
    NKLocation *endLocation = tracePoints.lastObject;
    endPoint.coordinate = CLLocationCoordinate2DMake(endLocation.nk_latitude, endLocation.nk_longitude);
    endPoint.title = @"end";
    [self.mapView addAnnotation:endPoint];
    
    CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(tracePoints.count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < tracePoints.count; i++)
    {
        coords[i] = CLLocationCoordinate2DMake(tracePoints[i].nk_latitude, tracePoints[i].nk_longitude);
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coords count:tracePoints.count];
    [self.mapView addOverlay:polyline];
    
    [self.mapView showOverlays:self.mapView.overlays edgePadding:UIEdgeInsetsMake(30, 50, 30, 50) animated:NO];
    
    if (coords)
    {
        free(coords);
    }
    
}

- (void)initDisplayAnnotationView {

    NSArray<NKLocation *> *annotationLocationArray = self.record.annotationLocationsArray;
    
    if (annotationLocationArray == nil) {
        return;
    }
    
    for (int i = 0; i < annotationLocationArray.count; i++) {
        
        NKLocation *location = annotationLocationArray[i];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(location.nk_latitude, location.nk_longitude);
        NKPointAnnotation *pointAnnotation = [[NKPointAnnotation alloc] init];
        pointAnnotation.coordinate = coordinate;
        pointAnnotation.title = [NSString stringWithFormat: @"%d",i+1];
        [self.mapView addAnnotation:pointAnnotation];

    }
    
}

// 查看照片
- (void)showPhoto:(UITapGestureRecognizer *)tapGestureRecognizer {
    
    CustomAnnotationView *annotationView = (CustomAnnotationView *)tapGestureRecognizer.view;
    NSInteger index = [annotationView.annotation.title integerValue] - 1;
    [self jumpToLookAnnotionWithIndex:index];
    
}

- (void)jumpToLookAnnotionWithIndex:(NSInteger) index {

    NKFIlePath *filePath = self.record.filePathArray[index] ;
    NKLookAnnotationViewController *lookVC = [[NKLookAnnotationViewController alloc] init];
    if ([filePath.imagePath isEqualToString:@"nil"]) {
        
        lookVC.imagePath = filePath.imagePath;;
        
    }else {
        
        lookVC.imagePath = [[FileHelper baseDir] stringByAppendingPathComponent:filePath.imagePath];
    }
    
    if ([filePath.audioPath isEqualToString:@"nil"]) {
        
        lookVC.audioPath = filePath.audioPath;;
        
    }else {
        
        lookVC.audioPath = [[FileHelper baseDir] stringByAppendingPathComponent:filePath.audioPath];
    }

    [self presentViewController:lookVC animated:YES completion:nil];
}

#pragma mark - mapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[NKPointAnnotation class]]) {
       
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.image = [UIImage imageNamed:@"audioPoint"];
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        annotationView.canShowCallout = NO;
        annotationView.selected = YES;
        annotationView.calloutView.title = annotation.title;
        [annotationView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPhoto:)]];
        return annotationView;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *annotationIdentifier = @"lcoationIdentifier";
        
        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
        
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
        }
        poiAnnotationView.pinColor = MAPinAnnotationColorGreen;
        poiAnnotationView.canShowCallout = YES;
        
        return poiAnnotationView;
    }
    
    
    return nil;

}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    
    if ([overlay isKindOfClass:[MAMutablePolyline class]])
    {
        MAMutablePolylineRenderer *view = [[MAMutablePolylineRenderer alloc] initWithMutablePolyline:overlay];
        view.lineWidth = 5.0;
        view.strokeColor = [UIColor redColor];
        return view;
    }
    
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *view = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        view.lineWidth = 4.0;
        view.strokeColor = [UIColor redColor];
        
        return view;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    if (view.annotation == self.myLocation)
    {
        [mapView selectAnnotation:self.myLocation animated:NO];
    }
}


#pragma mark - mapview delegate
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = views[0];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.image = [UIImage imageNamed:@"userPosition"];
        pre.lineWidth = 0.1;
        [self.mapView updateUserLocationRepresentation:pre];
        view.calloutOffset = CGPointMake(0, 0);
        self.userLocationAnnotationView = view;
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    
    if (!updatingLocation && self.userLocationAnnotationView != nil)
    {

        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
        }];
    }
    
    for (int i = 0; i < self.record.annotationLocationsArray.count; i++) {
        
        NKLocation *location = self.record.annotationLocationsArray[i];
        
        if ([[self doubleToNSString:location.nk_latitude] isEqualToString: [self doubleToNSString:userLocation.coordinate.latitude]] && [[self doubleToNSString:location.nk_longitude] isEqualToString: [self doubleToNSString:userLocation.coordinate.longitude]]) {
            
            [self jumpToLookAnnotionWithIndex:i];
           
        }
    }
}

- (NSString *)doubleToNSString:(double)value {

    return [NSString stringWithFormat:@"%.4f",value];
}

@end
